package com.hd.trans.network.factory;

import androidx.annotation.NonNull;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * SSE流文本解析
 */
public class SseStreamText {

    private final String source;
    private final List<SseEventData> dataList;

    public SseStreamText(String source) {
        this.source = source;
        this.dataList = new ArrayList<>();
    }

    public static SseStreamText parse(String response){
        boolean isJson = response.matches("^\\{.*\\}$");
        SseStreamText sseStreamText = new SseStreamText(response);
        if (isJson){
            sseStreamText.dataList.add(new SseEventData(UUID.randomUUID().toString(), "error", response));
        }
        else {
            String[] group = response.split("\n\n");
            for (String item : group) {
                String[] lines = item.split("\n");
                String id = null;
                String event = null;
                String data = null;
                for (String line : lines) {
                    if (line.startsWith("id: ")) {
                        id = line.substring(4);
                    } else if (line.startsWith("event: ")) {
                        event = line.substring(7);
                    } else if (line.startsWith("data: ")) {
                        data = line.substring(6);
                    }
                }
                if (event != null && data != null) {
                    sseStreamText.dataList.add(new SseEventData(id, event, data));
                }
            }
        }
        return sseStreamText;
    }

    public String getSource() {
        return source;
    }

    public List<SseEventData> getDataList() {
        return dataList;
    }

    @NonNull
    @Override
    public String toString() {
        return source;
    }

}
